package com.kern.academic.controller;

import com.alibaba.fastjson.JSONObject;
import com.kern.academic.bean.ResponseResult;
import com.kern.academic.bean.enumer.RemoveOperEnum;
import com.kern.academic.entity.XUser;
import com.kern.academic.service.IUserService;
import com.kern.academic.util.CommonUtil;
import com.kern.academic.vo.UserVO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Created by Cao Shi at 10:12 2021/6/26
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;

    /**
     * 查询用户
     * @param queryInfo
     * @return
     */
    @RequestMapping("/list")
    public ResponseResult listUsers(@RequestBody JSONObject queryInfo) {
        logger.info("====== 查询用户接口入参 ====== : [{}]", queryInfo);
        String search = queryInfo.getString("query");
        Integer pagenum = queryInfo.getInteger("pagenum");      // 前端传来的页码值是从1开始计数, 第一页页码是1
        Integer pagesize = queryInfo.getInteger("pagesize");
        return userService.listBySearchPage(search, pagenum - 1, pagesize);
    }

    /**
     * 修改用户状态
     * @param userInfo
     * @return
     */
    @RequestMapping("/changeState")
    public ResponseResult changeUserState(@RequestBody JSONObject userInfo) {
        logger.info("====== 修改用户状态接口入参 ====== : [{}]", userInfo);
        Boolean enable = userInfo.getBoolean("enable"); // 修改后的用户状态 true 启用, false 禁用
        XUser user = new XUser();
        user.setId(userInfo.getString("id"));
        user.setEnable(enable ? 1 : 0);
        XUser newuser;
        try {
            newuser = userService.update(user);
            if (newuser == null) {
                return ResponseResult.fail("当前用户不存在, 更新状态失败!");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResponseResult.fail("修改用户状态失败!");
        }

        return ResponseResult.ok("修改用户状态成功!", newuser);
    }


    @RequestMapping("/add")
    public ResponseResult addUser(@RequestBody JSONObject userInfo) {
        System.out.println("userInfo = " + userInfo);
        XUser user = new XUser();
        String id = CommonUtil.getUUID();
        user.setId(id);
        user.setUsername(userInfo.getString("username"));
        user.setPassword(userInfo.getString("password"));
        user.setEmail(userInfo.getString("email"));
        user.setPhone(userInfo.getString("phone"));
        user.setEnable(1);
        user.setCreatetime(new Date());
        XUser saveUser = userService.save(user);
        return ResponseResult.ok("新增用户成功", saveUser);
    }


    @GetMapping("/{id}")
    public ResponseResult getById(@PathVariable String id) {
       // System.out.println("id = " + id);
        XUser user = userService.getById(id);
        if (user == null) {
            return ResponseResult.fail("要查询的用户不存在!", id);
        }
        UserVO vo = new UserVO();
        vo.setUserId(id);
        vo.setUsername(user.getUsername());
        vo.setPhone(user.getPhone());
        vo.setEmail(user.getEmail());
        return ResponseResult.ok("查询用户成功!", vo);
    }

    @RequestMapping("/update")
    public ResponseResult updateUser(@RequestBody JSONObject params) {
        logger.info("====== 更新用户接口入参 ====== {}", params);
        String userId = params.getString("userId");
        if (StringUtils.isEmpty(userId)) {
            return ResponseResult.fail("用户Id为必传参数!");
        }
        XUser user = new XUser();
        user.setId(userId);
        user.setEmail(params.getString("email"));
        user.setPhone(params.getString("phone"));
        System.out.println(user);

        XUser updatedUser = userService.update(user);

        if (updatedUser != null) {
            return ResponseResult.ok("更新用户信息成功!", updatedUser);
        }
        return ResponseResult.fail("要更新的用户失败!");
    }


    @RequestMapping("/removeById")
    public ResponseResult removeUserById(@RequestBody JSONObject params) {
        logger.info("====== 根据id删除用户接口入参 ====== {}", params);
        String userId = params.getString("userId");
        if (StringUtils.isEmpty(userId)) {
            return ResponseResult.fail("用户Id为必传参数!");
        }
        RemoveOperEnum enu = userService.removeById(userId);

        if (enu.getCode() != 1) {
            return ResponseResult.fail(enu.getInfo());
        }
        return ResponseResult.ok("删除用户成功!");
    }

}
